<template>
  <div class="comment-container">
      <div class="comment-header">
          <span class="title">评论</span>
          <van-icon name="cross" @click="$emit('close')" />
      </div>

      <div class="comment-list">
          <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多评论了" @load="loadComments">
              <div v-for="comment in comments" :key="comment.id" class="comment-item">
                  <img :src="comment.author.avatar" class="avatar" />
                  <div class="comment-content">
                      <div class="comment-info">
                          <span class="username">{{ comment.author.username }}</span>
                          <span class="time">{{ formatTime(comment.createTime) }}</span>
                      </div>
                      <div class="comment-text">{{ comment.content }}</div>
                      <div class="comment-actions">
                          <div class="like" @click="handleLike(comment)">
                              <van-icon :name="comment.isLiked ? 'like' : 'like-o'"
                                  :color="comment.isLiked ? '#ff2c55' : '#999'" />
                              <span>{{ formatNumber(comment.likes) }}</span>
                          </div>
                          <div class="reply" @click="showReplyInput(comment)">
                              回复
                          </div>
                      </div>
                      <div v-if="comment.replies && comment.replies.length > 0" class="replies">
                          <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                              <img :src="reply.author.avatar" class="avatar" />
                              <div class="reply-content">
                                  <div class="reply-info">
                                      <span class="username">{{ reply.author.username }}</span>
                                      <span class="time">{{ formatTime(reply.createTime) }}</span>
                                  </div>
                                  <div class="reply-text">{{ reply.content }}</div>
                              </div>
                          </div>
                      </div>
                  </div>
              </div>
          </van-list>
      </div>

      <div class="comment-input">
          <van-field v-model="commentText" placeholder="说点什么..." :border="false" :autosize="{ maxHeight: 100 }">
              <template #button>
                  <van-button size="small" type="primary" :disabled="!commentText.trim()" @click="sendComment">
                      发送
                  </van-button>
              </template>
          </van-field>
      </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Toast } from 'vant'
import type { VideoComment } from '@/types/video'
import services from '@/services'

const props = defineProps<{
  videoId: string
}>()

defineEmits<{
  (e: 'close'): void
}>()

const comments = ref<VideoComment[]>([])
const loading = ref(false)
const finished = ref(false)
const page = ref(1)
const commentText = ref('')
const replyToComment = ref<VideoComment | null>(null)

const loadComments = async () => {
  if (loading.value) return
  loading.value = true
  try {
      const { items, total } = await services.comment.getComments(props.videoId, page.value)
      if (items.length > 0) {
          comments.value.push(...items)
          page.value++
      } else {
          finished.value = true
      }
  } catch (error) {
      Toast('加载评论失败')
  } finally {
      loading.value = false
  }
}

const sendComment = async () => {
  if (!commentText.value.trim()) return
  try {
      const newComment = await services.comment.addComment(
          props.videoId,
          commentText.value
      )
      comments.value.unshift(newComment)
      commentText.value = ''
      Toast('评论成功')
  } catch (error) {
      Toast('评论失败')
  }
}

const handleLike = async (comment: VideoComment) => {
  try {
      if (comment.isLiked) {
          await services.comment.unlikeComment(comment.id)
          comment.likes--
      } else {
          await services.comment.likeComment(comment.id)
          comment.likes++
      }
      comment.isLiked = !comment.isLiked
  } catch (error) {
      Toast('操作失败')
  }
}

const showReplyInput = (comment: VideoComment) => {
  replyToComment.value = comment
  commentText.value = `回复 @${comment.author.username}：`
}

const formatTime = (time: string): string => {
  const date = new Date(time)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  if (diff < 60000) {
      return '刚刚'
  } else if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前'
  } else if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前'
  } else {
      return Math.floor(diff / 86400000) + '天前'
  }
}

const formatNumber = (num: number): string => {
  if (num >= 10000) {
      return (num / 10000).toFixed(1) + 'w'
  }
  return num.toString()
}
</script>